package com.aphrodite.util.geom;

import java.util.Vector;

public final class Polygon extends Shape {
	private final Vector points = new Vector();

	public Polygon(int x, int y) {
		super(x, y);
	}

	/**
	 * Add a point to the polygon
	 * 
	 * @param point
	 */
	public final void addPoint(Point point) {
		points.addElement(point);
	}

	public final void addPoint(int x, int y) {
		addPoint(new Point(x, y));
	}

	public Point[] getPoints() {
		Point[] pts = new Point[points.size()];
		points.copyInto(pts);
		return pts;
	}

	/**
	 * Get the bounds of the polygon
	 * 
	 * @return A rectangle
	 */
	public Rectangle getBounds() {
		int MinX = 0xf423f;
		int MinY = 0xf423f;
		int MaxX = 0xfff0bdc1;
		int MaxY = 0xfff0bdc1;
		Point tmp;
		for (int i = 0; i < points.size(); i++) {
			tmp = (Point) points.elementAt(i);
			MinX = Math.min(MinX, tmp.x);
			MaxX = Math.max(MaxX, tmp.x);
			MinY = Math.min(MinY, tmp.y);
			MaxY = Math.max(MaxY, tmp.y);
		}

		return new Rectangle(MinX, MinY, MaxX - MinX, MaxY - MinY);

	}

	/**
	 * Check if the polygon contains this point
	 * 
	 * @param x
	 * @param y
	 * @return
	 */
	public boolean contains(int x, int y) {
		int i = 0;
		int j = 0;
		boolean c = false;
		i = 0;
		for (j = points.size() - 1; i < points.size(); j = i++)
			if ((getY(i) <= y && y < getY(j) || getY(j) <= y && y < getY(i))
					&& x < ((getX(j) - getX(i)) * (y - getY(i))) / (getY(j) - getY(i)) + getX(i))
				c = !c;

		return c;
	}

	public int getX(int i) {
		return ((Point) points.elementAt(i)).x;
	}

	public int getY(int i) {
		return ((Point) points.elementAt(i)).y;
	}
}
